package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.LoginVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class WeChatServiceImpl implements WeChatService {
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.framework.wechat.appid}")
    private   String appId;
    @Value("${zzyl.framework.wechat.secret}")
    private  String secret;

    @Override
    public String getOpenId(String code) {
        Map<String, Object> map =getAppConfig();
        map.put("js_code", code);
        String result = HttpUtil.get(REQUEST_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    private Map<String, Object> getAppConfig() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        return map;
    }

    @Override
    public String getPhone(String code) {
        String token = getToken();
        String url = PHONE_REQUEST_URL + token;
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(map));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.notEqual(jsonObject.getInt("errcode"),0)){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        String phone = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        return phone;
    }

    private String getToken() {
        Map<String, Object> map = getAppConfig();
        String result = HttpUtil.get(TOKEN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");

    }
}


